package com.scanner.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.scanner.entity.ScanRequest;
import com.scanner.ocr.abbyy.AbbyClient;
import com.scanner.service.ScanRequestService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);

	@Autowired
	private ScanRequestService scanRequestService;
	
	@Autowired
	private AbbyClient abbyClient;
	
	@RequestMapping(value = "/hello")
	public @ResponseBody
	String logoutUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return "Hello World";
	}
	
	
	@RequestMapping(value = "/recognizeText", method=RequestMethod.POST)
	public @ResponseBody
	String recognizeText(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		System.out.println("In multipart file request"+multipartFile.getOriginalFilename());
		
		String result = abbyClient.processTextRecognition(multipartFile.getBytes());
		ScanRequest scanRequest = new ScanRequest();
		scanRequest.setRequestFileName(multipartFile.getOriginalFilename());
		scanRequest.setOutPutText(result);

		scanRequestService.save(scanRequest);
		
		return result;
	}

}
